package edu.swust.graduation_project.eauction.activity

import android.content.SharedPreferences
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Looper
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import edu.swust.graduation_project.eauction.R
import java.sql.Connection
import java.sql.DriverManager
import java.text.SimpleDateFormat
import java.util.*


class ItemActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_item)
        val itemName = intent.getSerializableExtra("itemName").toString()
        val itemCreateTime = intent.getSerializableExtra("itemCreateTime").toString()
        val itemEndTime = intent.getSerializableExtra("itemEndTime").toString()
        val itemPrice = intent.getSerializableExtra("itemPrice").toString()
        val itemCreater = intent.getSerializableExtra("itemCreater").toString()
        val itemLastBid = intent.getSerializableExtra("itemLastBid").toString()
        val itemStringPrice = intent.getSerializableExtra("itemStartingPrice").toString()

        val itemCreateTimeDate =
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(itemCreateTime.toString())
        val itemEndTimeDate =
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(itemEndTime.toString())
        val itemIsDelivery = intent.getBooleanExtra("itemIsDelivery", false)

        val mIvItemIcon = findViewById<ImageView>(R.id.iv_itemicon)
        val mTvItemName = findViewById<TextView>(R.id.tv_item_name)
        val mTvItemCreater = findViewById<TextView>(R.id.tv_item_creater)
        val mTvItemBid = findViewById<TextView>(R.id.tv_item_bider)
        val mTvItemPrice = findViewById<TextView>(R.id.tv_item_price)
        val mTvItemStringPrice = findViewById<TextView>(R.id.tv_item_startingprice)
        val mTvItemCountdown = findViewById<TextView>(R.id.tv_item_countdown)
        val mEtItemPrice = findViewById<EditText>(R.id.et_item_price)
        val mBtnItemBid = findViewById<Button>(R.id.btn_item_bid)

        mTvItemName.text = itemName
        mTvItemCreater.text = itemCreater
        mTvItemBid.text = itemLastBid
        mTvItemPrice.text = itemPrice
        mTvItemStringPrice.text = itemStringPrice

        val mSharedPreferences: SharedPreferences =
            this@ItemActivity.getSharedPreferences(
                "user",
                AppCompatActivity.MODE_PRIVATE
            )
        val nowBider = mSharedPreferences.getString("username", "")

        if (itemCreater == nowBider) {
            mEtItemPrice.isEnabled = false
            mBtnItemBid.isEnabled = false
            mEtItemPrice.setText("不能给自己的商品竞价")
        }
        mBtnItemBid.setOnClickListener {
            if (mEtItemPrice.text.isNullOrBlank()) {
                Toast.makeText(this, "请输入您的出价", Toast.LENGTH_SHORT).show()
            } else if (mEtItemPrice.text.toString().toFloat() <=
                mTvItemPrice.text.toString().toFloat()
            ) {
                Toast.makeText(this, "您的出价应该高于现最高竞价", Toast.LENGTH_SHORT).show()
            } else {
                itemBidMysql(mEtItemPrice, nowBider, itemCreateTime)
            }
        }


        Glide.with(this)
            .load(
                "*" +
                        itemCreateTime.trim().replace(" ", "%20")
                            .replace(":", "%3A").replace(".0", "") +
                        ".png"
            )
            .into(mIvItemIcon)

        //倒计时模块
        val countDownTimer: CountDownTimer = object :
            CountDownTimer(itemEndTimeDate!!.time - Date(System.currentTimeMillis()).time, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                var value = (millisUntilFinished / 1000).toInt()
                val day: Int = value / (24 * 60 * 60)
                val hour: Int = (value - day * 24 * 60 * 60) / (60 * 60)//单位时
                val minute: Int =
                    (value - day * 24 * 60 * 60 - hour * (60 * 60)) / 60 //单位分
                val second: Int =
                    (value - day * 24 * 60 * 60 - hour * (60 * 60) - minute * 60)
                mTvItemCountdown.text =
                    "$day" + "天" + "$hour" + "小时" + "$minute" + "分钟" + "$second" + "秒"
            }

            override fun onFinish() {
                mEtItemPrice.isEnabled = false
                mTvItemCountdown.setText("拍卖已经结束")
                if (itemIsDelivery) {
                    mEtItemPrice.setText("已经创建订单")
                    mBtnItemBid.text = "拍卖已经结束"
                    mBtnItemBid.isEnabled = false
                } else if (nowBider == itemCreater) {
                    mEtItemPrice.isEnabled = false
                    mEtItemPrice.setText("等待创建订单")
                    mBtnItemBid.text = "创建订单"
                    mBtnItemBid.setOnClickListener {
                        createrDeliveryMysql(
                            itemCreateTime,
                            itemCreateTime.trim().replace(".0", ""),
                            itemLastBid,
                            itemCreater,
                            itemName
                        )
                    }
                } else {
                    mBtnItemBid.isEnabled = false
                    mEtItemPrice.setText("等待创建订单")
                    mBtnItemBid.text = "只有发起人才能创建订单"
                }
            }
        }
        countDownTimer.start()
    }

    private fun itemBidMysql(
        mEtItemPrice: EditText,
        bider: String?,
        itemCreateTime: String,
    ) {
        val price = mEtItemPrice.text.toString()
        object : Thread() {
            override fun run() {
                val UpdateSQL = "UPDATE `test_case`.`Item` SET `item_price` = " +
                        "'$price'" +
                        ", `item_last_bid` = " +
                        "'$bider'" +
                        " WHERE `Item`.`item_create_time` = '$itemCreateTime'"
                val cn: Connection = DriverManager.getConnection(
                    "*",
                    "*", "*"
                )
                val ps = cn.createStatement()
                ps.execute(UpdateSQL)
                ps.close()
                cn.close()
                finish()
                Log.d("EditUser", "上传成功")
            }
        }.start()
    }

    fun createrDeliveryMysql(
        itemCreateTime: String,
        itemCreateTimeDate: String,
        itemLastBid: String?,
        itemCreater: String,
        itemName: String,
    ) {
        object : Thread() {
            override fun run() {
                val UpdateItemSQL =
                    "UPDATE `test_case`.`Item` SET `item_is_delivery` = '1' WHERE `Item`.`item_create_time` = " +
                            "'$itemCreateTime';"
                val InsertDeliverySQL =
                    "INSERT INTO `test_case`.`Delivery` (`item_create_time`, `item_name`, `buyer`, `seller`, `seller_express_number`, `buyer_address`, `buyer_phone`, `seller_phone`) VALUES " +
                            "('$itemCreateTimeDate', '$itemName', '$itemLastBid', '$itemCreater', NULL, NULL, NULL, NULL);"
                try {
                    val cn: Connection = DriverManager.getConnection(
                        "*",
                        "*", "*"
                    )
                    val ps = cn.createStatement()
                    ps.execute(UpdateItemSQL)
                    ps.execute(InsertDeliverySQL)
                    ps.close()
                    cn.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                Looper.prepare()
                Toast.makeText(this@ItemActivity, "创建订单成功", Toast.LENGTH_SHORT).show()
                finish()
                Log.d("createrDeliveryMysql", "上传成功")
            }
        }.start()
    }
}